<script setup lang="ts">
  import dayjs from 'dayjs'
  import 'dayjs/locale/en'
  import 'dayjs/locale/zh-cn'
  import relativeTime from 'dayjs/plugin/relativeTime'
  import { computed, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import BaseEmpty from '~/components/BaseEmpty.vue'
  import settingArrow from '/images/png/setting/setting_arrow.png'
  import emptyIcon from '/images/webp/personal/empty-img.webp'
  const { t } = useI18n()

  // 配置 dayjs
  dayjs.extend(relativeTime)

  definePageMeta({
    layout: 'header-back',
    title: 'login_log'
  })

  // 定义登录日志类型
  interface LoginLog {
    browser: string
    region: string
    ip: string
    time: string
  }
  const {
    list: loginLogList,
    runAsync: loginLogRunAsync,
    page,
    page_size,
    total,
    prev,
    next
  } = useList(ApiMemberFrontLoginLogList, {}, { page_size: 10 })
  /** 过去时间转换 */
  function timeToFromNow(ts: number) {
    if (!ts) return '-'

    const timestamp = ts * 1000 // 转换为毫秒
    const targetTime = dayjs(timestamp)

    // 直接返回年月日时分秒格式
    return targetTime.format('YYYY.MM.DD HH:mm:ss')
  }

  // 地区代码映射
  const regionCodeMap = {
    China: 'CN',
    'United States': 'US',
    Japan: 'JP',
    Korea: 'KR',
    Singapore: 'SG',
    'Hong Kong': 'HK',
    Taiwan: 'TW',
    Macau: 'MO',
    Thailand: 'TH',
    Vietnam: 'VN',
    Malaysia: 'MY',
    Indonesia: 'ID',
    Philippines: 'PH',
    Australia: 'AU',
    'United Kingdom': 'GB',
    Germany: 'DE',
    France: 'FR',
    Italy: 'IT',
    Spain: 'ES',
    Russia: 'RU',
    Canada: 'CA',
    Brazil: 'BR',
    India: 'IN'
  }

  // 获取地区代码
  const getRegionCode = (region: string) => {
    if (!region) return '--'

    // 分割地区字符串，获取国家名称
    const country = region.split(' - ')[0]

    // 查找对应的地区代码
    const code = regionCodeMap[country as keyof typeof regionCodeMap]

    return code || '--'
  }

  const tableData = computed(() => {
    if (loginLogList) {
      return loginLogList.value.map(item => {
        const { browserName, isMobile } = getBrowserInfo(item.browser)
        const temp = {
          browser: browserName,
          near: getRegionCode(item.ipaddress), // 使用地区代码转换函数
          addr: item.loginip,
          lastUsed: item.created_at ? timeToFromNow(item.created_at) : '-'
        }
        return temp
      })
    }
  })
  console.log('tableData', tableData)
  // 登录日志数据
  const loginLogs = ref<LoginLog[]>([])

  // 监听 tableData 变化
  watch(
    tableData,
    newVal => {
      if (newVal) {
        loginLogs.value = newVal.map(item => ({
          browser: item.browser,
          region: item.near,
          ip: item.addr,
          time: item.lastUsed
        }))
      }
    },
    { immediate: true }
  )

  // 是否有日志数据
  const hasLogs = computed(() => loginLogs.value.length > 0)

  // 计算总页数
  const totalPages = computed(() => {
    console.log('total.value / page_size.value', total.value / page_size.value)

    return Math.ceil(total.value / page_size.value)
  })

  application.allSettled([loginLogRunAsync()])

  // 判断浏览器类型
  const getBrowserInfo = (ua: string) => {
    let browserName = ''
    if (ua.includes('Safari') && !ua.includes('Chrome')) {
      browserName = 'Safari'
    } else if (ua.includes('Chrome')) {
      browserName = 'Chrome'
    } else if (ua.includes('Firefox')) {
      browserName = 'Firefox'
    } else if (ua.includes('MSIE') || ua.includes('Trident/')) {
      browserName = 'IE'
    } else if (ua.includes('Edge')) {
      browserName = 'Edge'
    }

    // 判断是否是移动设备
    const isMobile = /iPhone|iPad|iPod|Android/i.test(ua)

    return {
      browserName,
      isMobile
    }
  }
</script>

<template>
  <div class="log-page">
    <!-- 登录日志部分 -->
    <div class="log-content">
      <!-- Tab 列表 -->
      <div class="tab-header">
        <div class="tab-item browser">{{ t('login_log_browser') }}</div>
        <div class="tab-item region">{{ t('login_log_region') }}</div>
        <div class="tab-item ip">IP</div>
        <div class="tab-item time">{{ t('login_log_login_time') }}</div>
      </div>

      <!-- 日志表格 -->
      <div v-if="hasLogs" class="log-table">
        <!-- 表格内容 -->
        <div class="table-body">
          <div v-for="(log, index) in loginLogs" :key="index" class="table-row">
            <div class="table-cell browser">
              {{ log.browser.length > 20 ? `${log.browser.slice(0, 20)}...` : log.browser }}
            </div>
            <div class="table-cell region">{{ log.region }}</div>
            <div class="table-cell ip">{{ log.ip }}</div>
            <div class="table-cell time">{{ log.time }}</div>
          </div>
        </div>
        <!-- 分页组件 -->
        <div v-if="hasLogs && totalPages > 1" class="pagination-container">
          <button class="pagination-btn" :disabled="page === 1" @click="prev()">
            <BaseImage width="13.95px" style="height: 13.95px" :url="settingArrow" />
          </button>
          <span class="page-info">
            <span class="current-page">{{ String(page).padStart(2, '0') }}</span>
            <span class="current-text">{{ t('的') }}</span>
            <span class="total-pages">{{ String(totalPages).padStart(2, '0') }}</span>
          </span>
          <button class="pagination-btn btn-left" :disabled="page === totalPages" @click="next()">
            <BaseImage
              width="13.95px"
              style="height: 13.95px; transform: rotate(180deg)"
              :url="settingArrow"
            />
          </button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <BaseEmpty :icon="emptyIcon" :description="t('login_log_no_data')" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .log-page {
    height: 100vh;
    background-color: #232626;
    color: #fff;
    display: flex;
    flex-direction: column;
  }

  .page-header {
    height: 50px;
    display: flex;
    align-items: center;
    position: relative;
    text-align: center;
    background-color: #232626;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .back-button {
      position: absolute;
      left: 10px;
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        width: 20px;
        height: 20px;
        border: solid #fff;
        border-width: 0 0 2px 2px;
        transform: rotate(45deg);
        display: inline-block;
      }
    }

    .page-title {
      flex: 1;
      font-size: 16px;
      font-weight: 500;
      color: #fff;
    }
  }

  .log-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    background-color: #232626;
  }

  .tab-header {
    display: flex;
    background-color: #292d2e;
    border-radius: 8px;
    margin: 15px;
    padding: 12px;
    height: 40px;
    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 14px;
      color: #fff;
      font-weight: 500;
    }
  }

  .log-table {
    background-color: #292d2e;
    border-radius: 8px;
    margin: 0 15px;
    overflow: hidden;

    .table-body {
      font-size: 14px;
      color: #b3bec1;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      background-color: rgba(255, 255, 255, 0.05);

      .table-row {
        display: contents;

        .table-cell {
          padding: 12px;
          text-align: center;
          word-break: break-all;
          white-space: normal;
        }

        &:nth-child(odd) .table-cell {
          background-color: #292d2e;
        }

        &:nth-child(even) .table-cell {
          background-color: #323738;
        }
      }
    }
    .pagination-container {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 20px 0;
      gap: 2px;

      .pagination-btn {
        background-color: #323738;
        border: none;
        color: #fff;
        font-size: 16px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 24px;
        height: 36px;
        border-top-left-radius: 6.98px;
        border-top-right-radius: 1.74px;
        border-bottom-right-radius: 1.74px;
        border-bottom-left-radius: 6.98px;
        &:disabled {
          opacity: 0.4;
          cursor: not-allowed;
        }
      }
      .btn-left {
        width: 24px;
        height: 36px;
        border-top-left-radius: 1.74px;
        border-top-right-radius: 6.98px;
        border-bottom-right-radius: 6.98px;
        border-bottom-left-radius: 1.74px;
      }
      .page-info {
        display: flex;
        align-items: center;
        background-color: #323738;
        border-radius: 1.74px;
        color: #fff;
        font-size: 12px;
        font-weight: 500;
        height: 36px;
        gap: 4px;
        padding: 0 4px;
        line-height: 1;
        .current-page {
          background-color: #444a4b;
          padding: 4px 6px;
          font-size: 12px;
          font-weight: 700;
          line-height: 1;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 36px;
          height: 28px;
          min-width: 27.91px;
          border-radius: 5.23px;
        }
        .current-text{
          color: #849194;
        }
        .total-pages {
          font-size: 12px;
          font-weight: 700;
          line-height: 1;
          width: 36px;
          height: 28px;
          min-width: 27.91px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;

    :deep(.base-empty) {
      padding-top: 50px;

      .flex {
        display: flex;
        justify-content: center;
      }

      .w-48 {
        width: 150px;
        height: auto;
      }

      .h-48 {
        height: auto;
      }

      .mt-4 {
        margin-top: 1rem;
      }

      p {
        color: #b3bec1;
        font-size: 14px;
      }
    }
  }

  .browser,
  .region,
  .ip,
  .time {
    flex: 1;
  }
</style>
